import java.sql.*;

public class DbTest2 {
    public static void main(String[] args) throws Exception {
//        execSql();
        getTables();
    }

    private static void getTables() throws Exception {
        ResultSet resultSet = null;
        Connection conn = getConn();
        System.out.println("schema:" + conn.getSchema());
        System.out.println("Catalog:" + conn.getCatalog());
        DatabaseMetaData dbmd = conn.getMetaData();
        // 表名列表
        String[] types = {"TABLE"};
        ResultSet rest = dbmd.getTables(null, null, "%", types);
        while (rest.next()) {
            String tablename = rest.getString("TABLE_NAME");
            System.out.println("tablename:"+tablename);
            try {
                resultSet = dbmd.getPrimaryKeys(null, null, tablename);
                while (resultSet.next()) {
                    String name = resultSet.getString("COLUMN_NAME");
                    System.out.println("Primykey Column name:" + name);
                }

                resultSet = dbmd.getIndexInfo(null, null, tablename, false, false);
                while (resultSet.next()) {
                    String name = resultSet.getString("COLUMN_NAME");
                    System.out.println("Index Column name:" + name);
                }
                resultSet = dbmd.getColumns(null, null, tablename, null);
                while (resultSet.next()) {
                    String name = resultSet.getString("COLUMN_NAME");
                    String type = resultSet.getString("TYPE_NAME");
                    int size = resultSet.getInt("COLUMN_SIZE");
                    System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static Connection getConn() throws Exception {
        String URL = "jdbc:mysql://140.143.26.196:3306/bitest?useUnicode=true&amp;characterEncoding=utf-8";
        String USER = "bitest";
        String PASSWORD = "BI!!test111";
        //1.加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");
        //2.获得数据库链接
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    private static void execSql() throws Exception {
        Connection conn = getConn();
        //3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("select * from user");
        //4.处理数据库的返回结果(使用ResultSet类)
        while (rs.next()) {
            System.out.println(rs.getString("user_name") + " "
                    + rs.getString("user_password"));
        }

        //关闭资源
        rs.close();
        st.close();
        conn.close();
    }
}
